import React, { useState, useRef, useMemo, useEffect } from 'react'
import assets from 'assets'
import { Toast } from 'antd-mobile'
import platformSupport from 'api/platform-support'
import lovelornUser, { LoginVO, BindingPhoneDTO, ThirdLoginVO, WxWebBindingPhoneDTO , VerifyCodeLoginDTO } from 'api/lovelorn-user'
import { useLoginContext } from 'modules/user/LoginContext'
import { geetTestVerifyCode } from 'utils/gt_noAuth'
import { withStore } from 'services/store'
import { httpPost } from 'services/http'
import './register.scss'

const RegisterModal: React.FC<{ registerSuccess?: Function }> = ({ registerSuccess, ...props }) => {
    const withThirdLoginData = withStore('thirdLoginData', {} as ThirdLoginVO)
    const useThirdLoginData = withThirdLoginData.getShareState
    const [locking, setLocking] = useState(false)
  const [countDown, setCountDown] = useState<number>(60)
  const [phoneNum, setPhoneNum] = useState<string>('')
  const [sendCodeText, setSendCodeText] = useState<string>('获取验证码')
  const [phoneErrTxt, setPhoneErrTxt] = useState<string>()
  const [code, setCode] = useState<string>('')
  const timing = useRef(null)
  //const [isDouble, setIsDouble] = useState(false);//防止按钮双击
  const doubleClick = useRef(null)
  doubleClick.current=false;
  const regexPhone = /^1\d{10}$/
  /** 发送验证码倒计时 */
  const handleCountDown = () => {
    setLocking(true)
    Toast.loading('正在获取验证码')
    timing.current = setInterval(() => {
      setCountDown(countDown => {
        countDown -= 1
        // let sendCodeTextTmp = `${countDown}s后重新获取 `
        if (countDown === 0) {
          setLocking(false)
          // sendCodeTextTmp = '获取验证码'
          clearInterval(timing.current)
          return 60
        }
        // setSendCodeText(sendCodeTextTmp)
        return countDown
      })
    }, 1000)
  }
  const sendCodeLabel = useMemo(() => {
    if (countDown < 60 && countDown > 0) return `${countDown}s后重新获取`
    return '获取验证码'
  }, [countDown])
  /** 发送验证码 */
  const handleSendCode = async () => {
    // console.warn('==发送验证码==', type)
    if (locking) return
    if (!regexPhone.test(phoneNum)) {
      setPhoneErrTxt('请输入正确的手机号')
      Toast.show('请输入正确的手机号')
      return
    }
    setPhoneErrTxt('')
    handleCountDown()
    let params = {
      serviceCode: 4,
      verifyKey: phoneNum,
      verifyType: '0',
    }
    let res = await geetTestVerifyCode(params)
    if (res.data && res.data.code == '200') {
      return
    }
    Toast.fail(res.data && res.data.msg ? res.data.msg : '网络出小差了')
  }
  const loginContext = useLoginContext()
  const thirdData = useThirdLoginData()
  const withThirdData = withThirdLoginData

  const confirm = async () => {
    if (doubleClick.current) {
			return;
    }
    doubleClick.current=true;
		if (!regexPhone.test(phoneNum)) {
      Toast.show('请输入正确的手机号')
      doubleClick.current=false;
			return
		}
		if (!code) {
      Toast.show('请输入验证码')
      doubleClick.current=false;
			return
		}
    // if (!thirdData.loginVO || !thirdData.loginVO.user || !thirdData.loginVO.user.userId) return
    // let param: WxWebBindingPhoneDTO = {
    //   //userId: thirdData.loginVO.user.userId,
    //   userId:523937678245888,
    //   userPhone: phoneNum,
    //   veriCode: code,
    // }
    let param:VerifyCodeLoginDTO= {
        verifyServiceCode:4,
        phone: phoneNum,
        verifyCode: code,
      }

    // lovelornUser.userThirdLogins
    //   .wxwebBindingPhone(param)
    httpPost(`/lovelorn-user/v1.2/pb/user-accounts/action/loginOrRegByVerifyCode`, param).then((res:any) => {
      console.log("rrrr",res)
      if(res.data.status==true){
        registerSuccess()
        doubleClick.current=false;
        loginContext.login(res.data.data)
        // withThirdData.setShareState(res.data.data)
        
      }else{
        Toast.fail(res.data.msg || '网络开小差啦');
        doubleClick.current=false;
      }
      
    }).catch(err => {
      Toast.fail(err.msg || '网络开小差啦');
      doubleClick.current=false;
    })
  }
  const inputCode = (e: React.ChangeEvent<HTMLInputElement>) => {
    let val = e.target.value
    if (val && val.length > 4) {
      val = val.slice(0, 4)
    }
    setCode(val)
  }
  const inputPhone = (e: React.ChangeEvent<HTMLInputElement>) => {
    let inputVal = e.target.value
    if (inputVal && inputVal.length > 11) {
      inputVal = inputVal.slice(0, 11)
    }
    setPhoneNum(inputVal)
  }
  const myFunction = useRef(null)

  useEffect(() => {
    var u = navigator.userAgent
    var flag

    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    if (isIOS) {
      document.body.addEventListener('focusin', () => {
        //软键盘弹起事件
        flag = true
        clearTimeout(myFunction.current)
      })
      document.body.addEventListener('focusout', () => {
        //软键盘关闭事件
        flag = false
        if (!flag) {
          myFunction.current = setTimeout(function () {
            window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }) //重点  =======当键盘收起的时候让页面回到原始位置(这里的top可以根据你们个人的需求改变，并不一定要回到页面顶部)
          }, 200)
        } else {
          return
        }
      })
    } else {
      return
    }
  }, [])
  return (
    <div className="register-modal-cooperation flexC">
      <img className="registerText" src={require('../../../assets/image/cooperationDetails/register_text.png')}></img>
      <div className="iptWrap">
      <div className="iptBox">
        <div className="titleBox flexR">
          <img className="icon icon_left" src={require('../../../assets/image/cooperationDetails/register_title_icon.png')}></img>
          <p className="text">账号绑定</p>
          <img className="icon icon_right" src={require('../../../assets/image/cooperationDetails/register_title_icon.png')}></img>
        </div>
        {/* <div className="phone-err">{phoneErrTxt}</div> */}
        <div className="ipt-row flexR">
          <img className="ipt-icon ipt-icon1" src={require('../../../assets/image/cooperationDetails/phone_icon.png')}></img>
          <input type="tel" placeholder="输入手机号" maxLength={11} value={phoneNum} onChange={inputPhone} />
          
        </div>
        <div className="ipt-row flexR">
          <img  className="ipt-icon ipt-icon2" src={require('../../../assets/image/cooperationDetails/keyword_icon.png')}></img>
          <input type="tel" placeholder="输入验证码" maxLength={4} onChange={inputCode} value={code} />
          <span onClick={handleSendCode} className={`sendCode flexR ${sendCodeLabel != '获取验证码' && 'graySendCode'}`}>{sendCodeLabel}</span>
        </div>
        <div
        onClick={confirm}
        className='submit-btn'>
       登录/注册
      </div>
      </div>
      <div id="captchaBox"></div>
      </div>
      
    </div>
  )
}
export default RegisterModal
